﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Smart_Archives.Entity;
using Smart_Archives.Models.Enum;
using Smart_Archives.Utils;

namespace Smart_Archives.Controllers
{
    /// <summary>
    /// 抓拍机控制器
    /// </summary>
    public class SnapController : Controller
    {
        private readonly SaContext _saContext;

        public SnapController(SaContext saContext)
        {
            _saContext = saContext;
        }

        public IActionResult Index()
        {
            var deviceId = Request.Query["id"].ToInt();
            var pageIndex = Request.Query["page"].ToInt(1);
            var minDate = Request.Query["minDate"];
            var maxDate = Request.Query["maxDate"];
            //            var model= _saContext.SecurityDevice.FirstOrDefault(a=>a.SecurityCategoryId==deviceId);
            //            var date = model.EventTime.Value.Date;
            var items = _saContext.SecurityDeviceRecord.Where(a => a.SecurityDeviceId == deviceId && a.EventType == Convert.ToInt32(EventTypeEnum.Snap)).OrderByDescending(a => a.CreateTime)
                .GroupBy(a => a.CreateTime.Value.Date);
            var device = _saContext.SecurityDevice.Find(deviceId);
            int pageSize = 10;
            if (!string.IsNullOrEmpty(minDate) || !string.IsNullOrEmpty(maxDate))
            {
                var minConvertDate = Convert.ToDateTime(minDate).Date;
                var maxConvertDate = Convert.ToDateTime(maxDate).Date.AddDays(1);
                items = items.Where(a => a.Key >= minConvertDate && a.Key < maxConvertDate);
            }

            var itemCount = items.Count();
            var pageCount = (int)Math.Ceiling(itemCount / (double)pageSize);
            var list = items.OrderByDescending(a => a.Key).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            ViewBag.itemCount = itemCount;
            ViewBag.pageCount = pageCount;
            ViewBag.location = device.Location;
            ViewBag.deviceName = device.Name;
            ViewBag.deviceId = device.Id;
            return View(list);
        }

        public ViewResult SnapList()
        {
            var deviceId = Request.Query["deviceId"].ToInt();
            var date = Convert.ToDateTime(Request.Query["date"]);
            var items = _saContext.SecurityDeviceRecord
                .Where(a => a.SecurityDeviceId == deviceId &&
                            a.CreateTime.Value.ToString("yyyy-MM-dd") == date.ToString("yyyy-MM-dd"))
                .OrderByDescending(a => a.CreateTime).ToList();
            return View(items);
        }
    }
}